package com.lwj.yuangong2.service.impl;

import com.lwj.yuangong2.dao.UserDao;
import com.lwj.yuangong2.entity.User;
import com.lwj.yuangong2.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@Transactional
public class UserServiceImpl  implements UserService {

    @Autowired
    private UserDao userDao;

    /**
     * 用户注册
     */
    @Override
    public void insertUser(User user) {
        //防止表单重复提交：查询用户名是否重复
        User userD = userDao.findByUserName(user.getUsername());
        if (userD == null) {
            //设置用户状态
            user.setStatus("已激活");
            //设置用户注册时间
            user.setRegisterTime(new Date());
            userDao.insertUser(user);
        }else {
            throw new RuntimeException("用户名已存在");
        }
    }

    /**
     * 用户登录
     */
    @Override
    public User login(User user) {
        //1.根据用户输入的用户名在数据库中查询  用户名不存在就登录失败
        User userDB = userDao.findByUserName(user.getUsername());
        if(userDB != null){  //不等于空也可以写成： !ObjectUtils.isEmpty(userDB)
            //2.比较密码 密码正确就登录成功 不正确就失败
            if (userDB.getPassword().equals(user.getPassword())){
                return userDB;
            }else {
                throw new RuntimeException("密码错误!");
            }
        }else {
            throw  new RuntimeException("用户名不存在!");
        }
    }
}
